package com.wetao.module_marking;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.PowerManager;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.target.CustomTarget;
import com.bumptech.glide.request.transition.Transition;
import com.wetao.lib_common.ConstantArouter;
import com.wetao.lib_common.Constants;
import com.wetao.lib_common.base.BaseActivity;
import com.wetao.lib_common.bean.track.TrackBean;
import com.wetao.lib_common.contract.EmptyCon;
import com.wetao.lib_common.presenter.EmptyPre;
import com.wetao.lib_common.service.PlayService_2;
import com.wetao.lib_common.utils.BaseEvent;
import com.wetao.lib_common.utils.ComUtil;
import com.wetao.lib_common.utils.DeviceInfoUtils;
import com.wetao.lib_common.utils.FileUtils;
import com.wetao.lib_common.utils.JsonUtils;
import com.wetao.lib_common.utils.LogUtils;
import com.wetao.lib_common.utils.ThreadPool;
import com.wetao.lib_common.utils.ToastUtil;
import com.wetao.lib_common.view.voicerecorder.EMError;
import com.wetao.lib_common.view.voicerecorder.VoiceRecorder;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.ref.WeakReference;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.OnClick;
import cn.hzw.doodle.DoodleOnTouchGestureListener;
import cn.hzw.doodle.DoodleParams;
import cn.hzw.doodle.DoodlePen;
import cn.hzw.doodle.DoodleTouchDetector;
import cn.hzw.doodle.DoodleView;
import cn.hzw.doodle.IDoodleListener;
import cn.hzw.doodle.core.IDoodle;
import cn.hzw.doodle.core.IDoodleItemListener;
import cn.hzw.doodle.core.IDoodleSelectableItem;
import cn.hzw.doodle.core.IDoodleTouchDetector;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.internal.operators.observable.ObservableInterval;
import io.reactivex.schedulers.Schedulers;

import static com.wetao.lib_common.view.voicerecorder.VoiceRecorderView.HANDLER_VOLUME;

@Route(path = ConstantArouter.PATH_MARKING_TRACKSYNCACTIVITY)
public class MarkingTrackSyncActivity extends BaseActivity<EmptyCon.View, EmptyPre>
        implements EmptyCon.View{
    private static final int HANDLER_TEST_DELAY_TIME = 900;
    private static final int HANDLER_TRACK_DRAWING = 901;
    private static final int HANDLER_TRACK_UNDO = 902;
    private static final int HANDLER_TRACK_LARGE_JUMPING = 903;
    private static final int HANDLER_AGAIN_RECORD_OR_PLAY= 904;
    private boolean isTest = true;
    private String mobile = "mobile"; //账号手机号，需要从后台拿
    private String keshi = "keshi"; //课时id，需要从后台拿
    private String shiti = "shiti"; //试题id，需要从后台拿
    private String test60shiti = "test60shiti"; //试题id，需要从后台拿

    private boolean hasFirstRecord = false;
    private boolean hasFirstPlay = false;

    private static final int handler_time_pre = 30;
    private float handler_time_scale = 1;
    private boolean isEraser = false;
    private boolean isWhiteboard = false;
    private boolean isGliding = false;
    private int mWhiteboardMaxPage = 10;
    private boolean isLargeJumping = false;
    private int fl_width;
    private int fl_height;

    private boolean isPx30Eink = false;
    private Disposable disposable;



    @BindView(R2.id.tv_recordStatus)
    TextView tv_recordStatus;
    @BindView(R2.id.tv_recordTime)
    TextView tv_recordTime;
    @BindView(R2.id.tv_recordVol)
    TextView tv_recordVol;
    @BindView(R2.id.tv_playTime)
    TextView tv_playTime;
    @BindView(R2.id.tv_playStatus)
    TextView tv_playStatus;
    @BindView(R2.id.fl_doodle)
    FrameLayout fl_doodle;
    @BindView(R2.id.iv_doodle_prev)
    ImageView iv_doodle_prev;
    @BindView(R2.id.iv_doodle_next)
    ImageView iv_doodle_next;
    @BindView(R2.id.btn_doodle_num)
    TextView btn_doodle_num;
    @BindView(R2.id.btn_eraser)
    Button btn_eraser;
    @BindView(R2.id.btn_Whiteboard)
    Button btn_Whiteboard;
    @BindView(R2.id.ll_record_1)
    LinearLayout ll_record_1;
    @BindView(R2.id.ll_record_2)
    LinearLayout ll_record_2;

    protected PowerManager.WakeLock wakeLock;

    private String voiceFilePath;
    protected int mMaxTime = 1 * 60 * 60 * 1000;
    protected VoiceRecorder voiceRecorder;
    private int mRecorderTime = 0;

    private PlayServiceConnection mPlayServiceConnection;
    private PlayService_2.PlayBinder playBinder;
    private PlayService_2 playService;
    private int mDuration;


    private int mDoodleImageIndex = 0;
    private List<String> mDoodleImagePath = new ArrayList<>();
    private List<Bitmap> mDoodle_bitmap_list = new ArrayList<>();
    private List<DoodleParams> mDoodleParams_list = new ArrayList<>();
    private List<IDoodle> mDoodle_list = new ArrayList<>();
    private List<DoodleView> mDoodleView_list = new ArrayList<>();
    private List<DoodleOnTouchGestureListener> mDoodleTouchGestureListener_list = new ArrayList<>();

    private int mWhiteboard_DoodleImageIndex = 0;
    private String mWhiteboard_DoodleImagePath;
    private Bitmap mWhiteboard_Doodle_bitmap;
    private List<DoodleParams>mWhiteboard_DoodleParams_list = new ArrayList<>();
    private List<IDoodle> mWhiteboard_Doodle_list = new ArrayList<>();
    private List<DoodleView> mWhiteboard_DoodleView_list = new ArrayList<>();
    private List<DoodleOnTouchGestureListener> mWhiteboard_DoodleTouchGestureListener_list = new ArrayList<>();


    private String trackFilePath;
    private int trackId = 0;
    private List<TrackBean> trackBeanList = new ArrayList<>();
    private int trackIndex_prev = 0;
    private int trackIndex_next = 0;
    private int playCurrentPosition_prev = 0;
    private int playCurrentPosition_next = 0;
    private int largeJumpTime = 0;
    private int largeJumpCount_max = 100;
    private int largeJumpCount = 0;

    private MyHandler handler;
    static class MyHandler extends Handler {
        WeakReference<MarkingTrackSyncActivity> weakReference;
        public MyHandler(MarkingTrackSyncActivity activity) {
            weakReference = new WeakReference(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            if(weakReference.get() == null) {
                return;
            }
            MarkingTrackSyncActivity activity = weakReference.get();
            if(msg.what == HANDLER_VOLUME) {
                activity.onSetVolume(msg.arg1, msg.arg2);
            }else if(msg.what == HANDLER_TRACK_LARGE_JUMPING) {
                if(msg.arg1 == 1) {
                    activity.callPauseMusic();
                } else if(msg.arg1 == 2) {
                    activity.callResumeMusic();
                }
            } else if(msg.what == HANDLER_AGAIN_RECORD_OR_PLAY) {
                if(activity.isLargeJumping) {
                    return;
                }
                if(msg.arg1 == 1) {
                    activity.startRecording();
                } else if(msg.arg1 == 2) {
                    activity.callPlayMusic();
                    activity.drawTrack_rxJava();
                }
            } else if(msg.what == HANDLER_TEST_DELAY_TIME) {

            }
        }
    }

    @Override
    public int getLayoutId() {
        return R.layout.marking_track_sync_activity;
    }

    @Override
    public EmptyPre createPresenter() {
        return new EmptyPre(this);
    }

    @Override
    public EmptyCon.View createView() {
        return this;
    }


    @Override
    public void init() {
        wakeLock = ((PowerManager) getSystemService(Context.POWER_SERVICE)).newWakeLock(
                PowerManager.SCREEN_DIM_WAKE_LOCK, "voice");

        handler = new MyHandler(this);

        String mDeviceProductName = DeviceInfoUtils.getDeviceProduct();
        LogUtils.i("设备名：" + mDeviceProductName);
        if(PlayService_2.PX30_EINK.equals(mDeviceProductName)) {
            isPx30Eink = true;
        }

        if(isPx30Eink) {
            ll_record_1.setVisibility(View.GONE);
            ll_record_2.setVisibility(View.GONE);
        }


        voiceRecorder = new VoiceRecorder(handler);

        Intent bindIntent = new Intent(this, PlayService_2.class);
        mPlayServiceConnection = new PlayServiceConnection();
        bindService(bindIntent, mPlayServiceConnection, Context.BIND_AUTO_CREATE);

        mDoodleImagePath.add("/sdcard/Android/data/com.wetao.teachertrain/files/mobile/audiotrack/keshi/shiti/pic_0.png");
        mDoodleImagePath.add("/sdcard/Android/data/com.wetao.teachertrain/files/mobile/audiotrack/keshi/shiti/pic_1.png");
        mDoodleImagePath.add("/sdcard/Android/data/com.wetao.teachertrain/files/mobile/audiotrack/keshi/shiti/pic_2.png");
        mDoodleImagePath.add("/sdcard/Android/data/com.wetao.teachertrain/files/mobile/audiotrack/keshi/shiti/pic_3.png");
        mDoodleImagePath.add("/sdcard/Android/data/com.wetao.teachertrain/files/mobile/audiotrack/keshi/shiti/pic_4.png");
        mDoodleImagePath.add("/sdcard/Android/data/com.wetao.teachertrain/files/mobile/audiotrack/keshi/shiti/pic_6.png");
        mDoodleImagePath.add("/sdcard/Android/data/com.wetao.teachertrain/files/mobile/audiotrack/keshi/shiti/pic_7.png");
        mWhiteboard_DoodleImagePath = "/sdcard/Android/data/com.wetao.teachertrain/files/mobile/audiotrack/keshi/shiti/pic_5.png";

        fl_doodle.post(new Runnable() {
            @Override
            public void run() {
                fl_width = fl_doodle.getMeasuredWidth();
                fl_height = fl_doodle.getMeasuredHeight();
                LogUtils.i("fl_doodle的宽：" + fl_width + ", 高" + fl_height);
            }
        });

        downLoadImg(false);

        if(isPx30Eink) {
            ComUtil.setWindowEpdMode(this, 2);
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        callStopMusic();
        cancelRecording();

    }

    @Override
    protected void onDestroy() {
        rxjava_disposable();
        if(mPlayServiceConnection != null) {
            unbindService(mPlayServiceConnection);
        }
        if(handler != null) {
            handler.removeCallbacksAndMessages(null);
            handler = null;
        }
        super.onDestroy();


        if(isPx30Eink) {
            ComUtil.setWindowEpdMode(this, 0);
        }
    }

    @OnClick({
            R2.id.btn_startRecord,
            R2.id.btn_pauseRecord,
            R2.id.btn_resumeRecord,
            R2.id.btn_completeRecord,
            R2.id.btn_againRecord,
            R2.id.btn_eraser,
            R2.id.btn_Whiteboard,
            R2.id.btn_revoke,
            R2.id.btn_unrevoke,
            R2.id.btn_play,
            R2.id.btn_pause,
            R2.id.btn_resume,
            R2.id.btn_stop,
            R2.id.btn_fastForward_0_75,
            R2.id.btn_fastForward_1_0,
            R2.id.btn_fastForward_2_0,
            R2.id.btn_fastForward_10m,
            R2.id.btn_fastForward_10p,
            R2.id.btn_fastForward_95p,
            R2.id.btn_test60Mi,
            R2.id.iv_doodle_prev,
            R2.id.iv_doodle_next,
            R2.id.btn_testDelay,
    })
    public void onViewClicked(View view) {
        if (view.getId() == R.id.btn_startRecord) {
            if(isTest) {
                fileOperate();
            }
            if(hasFirstRecord) {
                again_recording_or_play(false);
            } else {
                hasFirstRecord = true;
                startRecording();
            }

        } else if(view.getId() == R.id.btn_pauseRecord) {
            pauseRecording();
        } else if(view.getId() == R.id.btn_resumeRecord) {
            resumeRecording();
        } else if(view.getId() == R.id.btn_completeRecord) {
            completeRecord();
        } else if(view.getId() == R.id.btn_againRecord) {
            if(isTest) {
                fileOperate();
            }
            again_recording_or_play(false);
        } else if(view.getId() == R.id.btn_eraser) {
            switchEraser();
        } else if(view.getId() == R.id.btn_Whiteboard) {
            switchWhiteboard(false);
        } else if(view.getId() == R.id.btn_revoke) {
            if (!isWhiteboard && !mDoodle_list.get(mDoodleImageIndex).undo()) {
                ToastUtil.initToast("无法再撤销");
            }else if (isWhiteboard && !mWhiteboard_Doodle_list.get(mWhiteboard_DoodleImageIndex).undo()) {
                ToastUtil.initToast("无法再撤销");
            } else {
                writeActionToFile("ACTION_UNDO");
            }
        } else if(view.getId() == R.id.btn_unrevoke) {
            if (!isWhiteboard && !mDoodle_list.get(mDoodleImageIndex).redo(1)) {
                ToastUtil.initToast("无法再反撤销");
            } else if (isWhiteboard && !mWhiteboard_Doodle_list.get(mWhiteboard_DoodleImageIndex).redo(1)) {
                ToastUtil.initToast("无法再反撤销");
            }else {
                writeActionToFile("ACTION_REDO");
            }
        }else if(view.getId() == R.id.btn_play) {
            if(isTest) {
                fileOperate();
                setPlayMusicUrl(voiceFilePath);
            }
            //callPlayMusic();
            again_recording_or_play(true);
        } else if(view.getId() == R.id.btn_pause) {
            callPauseMusic();
        } else if(view.getId() == R.id.btn_resume) {
            callResumeMusic();
        } else if(view.getId() == R.id.btn_stop) {
            callStopMusic();
        } else if(view.getId() == R.id.btn_fastForward_0_75) {
            callPlaySpeed(0.75f);
        } else if(view.getId() == R.id.btn_fastForward_1_0) {
            callPlaySpeed(1.0f);
        } else if(view.getId() == R.id.btn_fastForward_2_0) {
            callPlaySpeed(2.0f);
        } else if(view.getId() == R.id.btn_fastForward_10m) {
            if(playCurrentPosition_next + 10 * 1000 > mDuration - 10 * 1000) {
                LogUtils.e("快进10秒后，剩余的秒数少于10秒，则不做快进");
            } else {
                largeJump(playCurrentPosition_next + 10 * 1000);
            }

        } else if(view.getId() == R.id.btn_fastForward_10p) {
            if(mDuration * 0.1 <= 10 * 1000) {
                LogUtils.e("时长的10%少于10秒，不做快进10%");
            } else if(playCurrentPosition_next + mDuration * 0.1 > mDuration - 10 * 1000) {
                LogUtils.e("当前时长加时长的10%， 剩余的秒数少于10秒, 不做快进10%");
            } else {
                largeJump(playCurrentPosition_next + (int)(mDuration * 0.1));
            }

        }else if(view.getId() == R.id.btn_fastForward_95p) {
            if(mDuration  < 60 * 1000) {
                LogUtils.e("时长少于60秒，不做拖动到95%");
            } else if(mDuration * 0.95 - playCurrentPosition_next < 10) {
                LogUtils.e("时长的95%减当前时间小于10秒，不做拖动到95%");
            } else {
                largeJump((int)(mDuration * 0.95));
            }

        } else if(view.getId() == R.id.iv_doodle_prev) {
            prevPage();
        } else if(view.getId() == R.id.iv_doodle_next) {
            nextPage();
        }else if(view.getId() == R.id.btn_test60Mi) {
            testFileOperate60mi();
            setPlayMusicUrl(voiceFilePath);
            again_recording_or_play(true);
        }else if(view.getId() == R.id.btn_testDelay) {
            Observable.interval(3, TimeUnit.MILLISECONDS)
                    .subscribeOn(Schedulers.single())
                    .subscribe(new Observer < Long > () {
                        @Override
                        public void onSubscribe(Disposable d) {

                        }

                        @Override
                        public void onNext(Long aLong) {
                            LogUtils.i("线程时间：" + (System.currentTimeMillis() - PlayService_2.testTime_2) + ", 线程名：" + Thread.currentThread().getName());
                            PlayService_2.testTime_2 = System.currentTimeMillis();
                        }

                        @Override
                        public void onError(Throwable e) {

                        }

                        @Override
                        public void onComplete() {

                        }
                    });
        }
    }

    private boolean  fileOperate() {
        if (!FileUtils.isSdcardExist()) {
            ToastUtil.initToast( "SD卡不存在");
            return false;
        }
        String dirPath = getExternalFilesDir(null).getAbsolutePath();

        String voiceDirPath = dirPath + File.separator + mobile + File.separator + "audiotrack" + File.separator + keshi + File.separator + shiti;
        File voiceDir = new File(voiceDirPath);
        if (!voiceDir.exists()) {
            boolean mkdirs = voiceDir.mkdirs();
            if (!mkdirs) {
                LogUtils.e("创建失败voiceDir：" + mkdirs);
                return false;
            } else {
                LogUtils.i("创建成功voiceDir");
            }
        }

        voiceFilePath = voiceDir + File.separator + "11.mp3";
        trackFilePath = voiceDir + File.separator + "track.txt";
        return true;
    }

    private boolean  testFileOperate60mi() {
        if (!FileUtils.isSdcardExist()) {
            ToastUtil.initToast( "SD卡不存在");
            return false;
        }
        String dirPath = getExternalFilesDir(null).getAbsolutePath();

        String voiceDirPath = dirPath + File.separator + mobile + File.separator + "audiotrack" + File.separator + keshi + File.separator + test60shiti;
        File voiceDir = new File(voiceDirPath);
        if (!voiceDir.exists()) {
            boolean mkdirs = voiceDir.mkdirs();
            if (!mkdirs) {
                LogUtils.e("创建失败voiceDir：" + mkdirs);
                return false;
            } else {
                LogUtils.i("创建成功voiceDir");
            }
        }

        voiceFilePath = voiceDir + File.separator + "11.mp3";
        trackFilePath = voiceDir + File.separator + "track.txt";
        return true;
    }

    public void startRecording() {
        if(voiceRecorder.getRecordStatus() != VoiceRecorder.VOICE_RECORDER_IDE
            && voiceRecorder.getRecordStatus() != VoiceRecorder.VOICE_RECORDER_COMPLETE) {
            ToastUtil.initToast("不能点两次开始录制");
            return;
        }
        if(!fileOperate()) {
            return;
        }

        File trackFile = new File(trackFilePath);
        if(trackFile.exists()) {
            trackFile.delete();
        }

        voiceRecorder.setVoiceFilePath(voiceFilePath);

        try {
            onVoiceStartRecording();
            wakeLock.acquire();
            voiceRecorder.startRecording(this);
        } catch (Exception e) {
            e.printStackTrace();
            if (wakeLock.isHeld())
                wakeLock.release();
            if (voiceRecorder != null)
                voiceRecorder.discardRecording();
            onVoiceRecordFail();
            ToastUtil.initToast("录音失败");
            return;
        }
    }

    private void pauseRecording() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            if(voiceRecorder.getRecordStatus() != VoiceRecorder.VOICE_RECORDER_START) {
                ToastUtil.initToast("只有在正在录制时，才能暂停");
                return;
            }
            onVoicePauseRecording();
            voiceRecorder.pauseRecording();
        }
    }

    private void resumeRecording() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            if(voiceRecorder.getRecordStatus() != VoiceRecorder.VOICE_RECORDER_PAUSE) {
                ToastUtil.initToast("只有在暂停录制时，才能恢复录制");
                return;
            }
            onVoiceResumeRecording();
            voiceRecorder.resumeRecording();
        }
    }

    private void completeRecord() {
        if(voiceRecorder.getRecordStatus() == VoiceRecorder.VOICE_RECORDER_START
            || voiceRecorder.getRecordStatus() == VoiceRecorder.VOICE_RECORDER_PAUSE) {
            try {
                int length = stopRecoding();
                if (length > 0) {
                    onVoiceRecordComplete(getVoiceFilePath(), length);
                } else if (length == EMError.FILE_INVALID) {
                    onVoiceRecordFail();
                    ToastUtil.initToast( "没有录音权限，录音失败");
                } else {
                    onVoiceRecordFail();
                    ToastUtil.initToast("录音时间太短，录音失败");
                }
            } catch (Exception e) {
                e.printStackTrace();
                // Toast.makeText(context, R.string.send_failure_please, Toast.LENGTH_SHORT).show();
            }
        } else {
            ToastUtil.initToast( "只有正在录制或者暂停录制时，才能点击完成录制");
        }

    }

    private void cancelRecording() {
        discardRecording();
    }

    private void again_recording_or_play(boolean isPlay) {

        handler_time_scale = 1;
        isEraser = false;
        isWhiteboard = false;
        isGliding = false;
        isLargeJumping = false;

        fl_doodle.removeAllViews();


        voiceRecorder.stopRecoding();
        playBinder.callStopMusic();
        mDuration = 0;


        mDoodleImageIndex = 0;
        mDoodle_bitmap_list = new ArrayList<>();
        mDoodleParams_list = new ArrayList<>();
        mDoodle_list = new ArrayList<>();
        mDoodleView_list = new ArrayList<>();
        mDoodleTouchGestureListener_list = new ArrayList<>();

        mWhiteboard_DoodleImageIndex = 0;
        mWhiteboard_Doodle_bitmap = null;
        mWhiteboard_DoodleParams_list = new ArrayList<>();
        mWhiteboard_Doodle_list = new ArrayList<>();
        mWhiteboard_DoodleView_list = new ArrayList<>();
        mWhiteboard_DoodleTouchGestureListener_list = new ArrayList<>();


        trackId = 0;
        trackBeanList = new ArrayList<>();
        trackIndex_prev = 0;
        trackIndex_next = 0;
        playCurrentPosition_prev = 0;
        playCurrentPosition_next = 0;
        largeJumpTime = 0;

        downLoadImg(false);

        Message msg = handler.obtainMessage();
        msg.what = HANDLER_AGAIN_RECORD_OR_PLAY;
        msg.arg1 = isPlay?2:1;
        handler.sendMessageDelayed(msg, 500);



    }

    private void onVoiceStartRecording() {
        tv_recordStatus.setText("开始录音");
        setSupportDoodle(true);
    }
    private void onVoicePauseRecording() {
        tv_recordStatus.setText("暂停录音");
        setSupportDoodle(false);
    }
    private void onVoiceResumeRecording() {
        tv_recordStatus.setText("恢复录音");
        setSupportDoodle(true);
    }

    private void onVoiceRecordComplete(String voiceFilePath, int voiceTimeLength) {
        mRecorderTime = voiceTimeLength;
        tv_recordTime.setText("时间：" + (int)(voiceTimeLength/1000));
        tv_recordStatus.setText("完成录音");
        setPlayMusicUrl(voiceFilePath);
        setSupportDoodle(false);
    }

    private void onVoiceRecordFail() {
        tv_recordStatus.setText("录音失败");
        setSupportDoodle(false);
    }

    private void setSupportDoodle(boolean isSupport) {
        if(!isWhiteboard && mDoodleTouchGestureListener_list.get(mDoodleImageIndex) != null) {
            mDoodleTouchGestureListener_list.get(mDoodleImageIndex).setSupportDoodle(isSupport);
        } else if(isWhiteboard && mWhiteboard_DoodleTouchGestureListener_list.get(mWhiteboard_DoodleImageIndex) != null) {
            mWhiteboard_DoodleTouchGestureListener_list.get(mWhiteboard_DoodleImageIndex).setSupportDoodle(isSupport);
        }
    }
    private void onSetVolume(int volume, int second) {
        mRecorderTime = second;
        tv_recordTime.setText("时间：" + (int)(second / 1000));
        tv_recordVol.setText("音量：" + volume);

        if(second >= mMaxTime) {
            completeRecord();
        }
    }

    public void discardRecording() {
        if (wakeLock.isHeld())
            wakeLock.release();
        try {
            // stop recording
            if (voiceRecorder.getRecordStatus() == VoiceRecorder.VOICE_RECORDER_START
                    || voiceRecorder.getRecordStatus() == VoiceRecorder.VOICE_RECORDER_PAUSE) {
                voiceRecorder.discardRecording();
                onVoiceRecordFail();
            }
        } catch (Exception e) {
        }
    }

    public int stopRecoding() {
        if (wakeLock.isHeld())
            wakeLock.release();
        return voiceRecorder.stopRecoding();
    }

    public String getVoiceFilePath() {
        return voiceRecorder.getVoiceFilePath();
    }


    public void setVoiceFilePath(String voiceFilePath) {
        voiceRecorder.setVoiceFilePath(voiceFilePath);
    }



    private class PlayServiceConnection implements ServiceConnection {
        @Override
        public void onServiceConnected(ComponentName name, IBinder binder) {
            playBinder = (PlayService_2.PlayBinder) binder;
            String testData = playBinder.getServiceTestData();
            LogUtils.i(testData);
            playService = playBinder.getService();
            if(isTest) {
                fileOperate();
                setPlayMusicUrl(voiceFilePath);
            }
            playService.setCallback(new PlayService_2.CallbackPlay() {
                @Override
                public void onDataTestChange(String data) {
                    LogUtils.i(data);
                }

                @Override
                public void onMusicStausChange(int status) {
                    //setPlayView(status);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            LogUtils.i("播放状态：" + status);
                            showMusicStatus();
                            if(playBinder != null) {
                                if (playBinder.callPlayStatus() != PlayService_2.STATUS_MUSIC_PLAY) {

                                }
                            }
                        }
                    });
                }

                @Override
                public void onCurrentPosition(int currentPosition, int duration) {

                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            //setCurAndTotalView(bundle);
                            //LogUtils.i("播放时间：" + currentPosition + "/" + duration);
                            tv_playTime.setText(currentPosition + "/" + duration);
                            playCurrentPosition_next = currentPosition;
                            if(playBinder != null) {
                                if (playBinder.callPlayStatus() == PlayService_2.STATUS_MUSIC_PLAY) {
                                } else {
                                    if (currentPosition == 0) {
                                        if (duration != 0) {
                                            mDuration = duration;
                                        }
                                    }
                                }
                            }
                        }
                    });
                }

                @Override
                public void OnDuration(int duration) {
                    LogUtils.i("总时长：" + duration);
                }

                @Override
                public void onCompletion() {
                    delay_rxjava_disposable();
                }
            });
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
        }
    }


    private void setPlayMusicUrl(String url) {
        if(playBinder != null) {
            playBinder.callSetmUrl(url);
        }
    }



    private void callPlayMusic() {
        if(playBinder != null) {
            if(playBinder.callPlayStatus() == PlayService_2.STATUS_MUSIC_IDE
                    || playBinder.callPlayStatus() == PlayService_2.STATUS_MUSIC_COMPLETE
            ) {
                lineReadFile();
                //playBinder.callPlayMusic();
            }
        }
    }

    private void callPauseMusic() {
        if(playBinder != null) {
            if(playBinder.callPlayStatus() == PlayService_2.STATUS_MUSIC_PLAY
            ) {
                playBinder.callPauseMusic();
            }
        }
    }

    private void callResumeMusic() {
        if(playBinder != null) {
            if(playBinder.callPlayStatus() == PlayService_2.STATUS_MUSIC_PAUSE
            ) {
                playBinder.callResumeMusic();
            }
        }
    }

    private void callStopMusic() {
        if(playBinder != null) {
            if(playBinder.callPlayStatus() == PlayService_2.STATUS_MUSIC_PLAY
                    || playBinder.callPlayStatus() == PlayService_2.STATUS_MUSIC_PAUSE
            ) {
                playBinder.callStopMusic();
                delay_rxjava_disposable();

            }
        }
    }

    private void callPlaySpeed(float speed) {
        if(isLargeJumping) {
            return;
        }
        if(playBinder != null) {
            if(playBinder.callPlayStatus() == PlayService_2.STATUS_MUSIC_PLAY
            ) {
                handler_time_scale = speed;
                playBinder.callPlaySpeed(speed);
                rxjava_disposable();
                drawTrack_rxJava();
            }
        }
    }

    private void callSeekTo(int position) {
        if(playBinder != null) {
            if(playBinder.callPlayStatus() == PlayService_2.STATUS_MUSIC_PAUSE
            ) {
                playBinder.callSeekTo(position);
            }
        }
    }

    private void largeJump(int time) {
        if(isLargeJumping || isGliding) {
            return;
        }
        if(playBinder != null) {
            if(playBinder.callPlayStatus() == PlayService_2.STATUS_MUSIC_PLAY
            ) {

                rxjava_disposable();
                largeJumpTime = time;
                isLargeJumping = true;
                handler_time_scale = 10;
                LogUtils.i("跳转 largeJumpTime = " + largeJumpTime);
                callPauseMusic();
                drawTrack_rxJava();
            }
        }
    }

    private void showMusicStatus() {
        if(playBinder != null) {
            switch (playBinder.callPlayStatus()) {
                case PlayService_2.STATUS_MUSIC_IDE_PRE:{
                    tv_playStatus.setText("初始化之前");
                }break;
                case PlayService_2.STATUS_MUSIC_IDE:{
                    tv_playStatus.setText("初始化");
                }break;
                case PlayService_2.STATUS_MUSIC_PLAY:{
                    tv_playStatus.setText("播放");
                }break;
                case PlayService_2.STATUS_MUSIC_PAUSE:{
                    tv_playStatus.setText("暂停");
                }break;
                case PlayService_2.STATUS_MUSIC_STOP:{
                    tv_playStatus.setText("停止");
                }break;
                case PlayService_2.STATUS_MUSIC_COMPLETE:{
                    tv_playStatus.setText("播放完成");
                }break;
            }
        }
    }




    private void downLoadImg(boolean isPlay) {
        final String f_url = isWhiteboard ? mWhiteboard_DoodleImagePath : mDoodleImagePath.get(mDoodleImageIndex);
        isGliding = true;
        Glide.with(this).asBitmap().load(f_url).skipMemoryCache(true).diskCacheStrategy(DiskCacheStrategy.NONE)
                .into(new CustomTarget<Bitmap>() {
                    @Override
                    public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                        isGliding = false;
                        Thread thread1 = getMainLooper().getThread();
                        Thread thread2 = Thread.currentThread();

                        LogUtils.i("-----doodle----glide主线程ID: "+thread1.getId() );
                        LogUtils.i("-----doodle----glide当前线程ID: "+thread2.getId() );

                        LogUtils.i("Glde图片-成功 url = " + f_url);
                        if(isWhiteboard) {
                            mWhiteboard_Doodle_bitmap = resource;
                        } else {
                            mDoodle_bitmap_list.add(resource);
                        }


                        initDoodleData(isPlay);
                    }

                    @Override
                    public void onLoadFailed(@Nullable Drawable errorDrawable) {
                        super.onLoadFailed(errorDrawable);
                        isGliding = false;
                        LogUtils.e("Glde图片-失败 url = " + f_url);
                    }

                    @Override
                    public void onLoadCleared(@Nullable Drawable placeholder) {

                    }
                });
    }

    private void set_btn_doodle_num(){
        if(isWhiteboard) {
            btn_doodle_num.setText((mWhiteboard_DoodleImageIndex + 1) + "/" + mWhiteboard_DoodleView_list.size());
            if(mWhiteboard_DoodleImageIndex >= mWhiteboard_DoodleView_list.size() - 1){
                iv_doodle_next.setImageResource(R.drawable.ic_collapse_selected);
            } else {
                iv_doodle_next.setImageResource(R.drawable.marking_doodle_next);
            }
        } else {
            btn_doodle_num.setText((mDoodleImageIndex + 1) + "/" + mDoodleImagePath.size());
            iv_doodle_next.setImageResource(R.drawable.marking_doodle_next);
        }
    }

    private void initDoodleData(boolean isPlay) {
        //fl_doodle.removeAllViews();
        DoodleParams mDoodleParams = new DoodleParams();
        if(isWhiteboard) {
            mDoodleParams.mImagePath = mWhiteboard_DoodleImagePath;
            mDoodleParams.mSavePath = mWhiteboard_DoodleImagePath;
        } else {
            mDoodleParams.mImagePath = mDoodleImagePath.get(mDoodleImageIndex);
            mDoodleParams.mSavePath = mDoodleImagePath.get(mDoodleImageIndex);
        }
        mDoodleParams.mSavePathIsDir = false;
        mDoodleParams.mIsDrawableOutside = false;


        /*
        Whether or not to optimize drawing, it is suggested to open, which can optimize the drawing speed and performance.
        Note: When item is selected for editing after opening, it will be drawn at the top level, and not at the corresponding level until editing is completed.
        是否优化绘制，建议开启，可优化绘制速度和性能.
        注意：开启后item被选中编辑时时会绘制在最上面一层，直到结束编辑后才绘制在相应层级
         */

        IDoodle mDoodle = null;
        DoodleView mDoodleView = null;
        mDoodle = mDoodleView = new DoodleViewWrapper(this, isWhiteboard ? mWhiteboard_Doodle_bitmap : mDoodle_bitmap_list.get(mDoodleImageIndex), mDoodleParams.mOptimizeDrawing, new IDoodleListener() {
            @Override
            public void onSaved(IDoodle doodle, Bitmap bitmap, Runnable callback) { // 保存图片为jpg格式
                LogUtils.i("-----doodle----onSaved");
                Thread thread1 = getMainLooper().getThread();
                Thread thread2 = Thread.currentThread();

                LogUtils.i("-----doodle----doodleViewWrapper主线程ID: "+thread1.getId() );
                LogUtils.i("-----doodle----doodleViewWrapper当前线程ID: "+thread2.getId() );
            }

            @Override
            public void onReady(IDoodle doodle) {
                LogUtils.i("-----doodle----onReady");
            }
        });

        DoodleOnTouchGestureListener mTouchGestureListener = new DoodleOnTouchGestureListener(mDoodleView, new DoodleOnTouchGestureListener.ISelectionListener() {

            IDoodleItemListener mIDoodleItemListener = new IDoodleItemListener() {
                @Override
                public void onPropertyChanged(int property) {

                }
            };

            @Override
            public void onSelectedItem(IDoodle doodle, IDoodleSelectableItem selectableItem, boolean selected) {

            }

            @Override
            public void onCreateSelectableItem(IDoodle doodle, float x, float y) {

            }

            @Override
            public void onCallScrollBegin(MotionEvent e) {
                writeEventTofile(e);
            }

            @Override
            public void onCallScrollEnd(MotionEvent e) {
                writeEventTofile(e);
            }

            @Override
            public void onCallScroll(MotionEvent e) {
                writeEventTofile(e);
            }
        }) {
            @Override
            public void setSupportScaleItem(boolean supportScaleItem) {
                super.setSupportScaleItem(supportScaleItem);
            }
        };

        mTouchGestureListener.setSupportScale(false); //禁止放大缩小
        if(voiceRecorder.getRecordStatus() != VoiceRecorder.VOICE_RECORDER_START) {
            mTouchGestureListener.setSupportDoodle(false); //禁止涂鸦
        } else {
            mTouchGestureListener.setSupportDoodle(true); //禁止涂鸦
        }
        mTouchGestureListener.setTouchType(DoodleOnTouchGestureListener.TOUCH_TYPE_ALL);
        IDoodleTouchDetector detector = new DoodleTouchDetector(getApplicationContext(), mTouchGestureListener);
        mDoodleView.setDefaultTouchDetector(detector);

        mDoodle.setIsDrawableOutside(mDoodleParams.mIsDrawableOutside);
        fl_doodle.addView(mDoodleView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        mDoodle.setDoodleMinScale(mDoodleParams.mMinScale);
        mDoodle.setDoodleMaxScale(mDoodleParams.mMaxScale);
        //mDoodle.setSize(2);

        if(isWhiteboard) {
            mWhiteboard_DoodleParams_list.add(mDoodleParams);
            mWhiteboard_Doodle_list.add(mDoodle);
            mWhiteboard_DoodleView_list.add(mDoodleView);
            mWhiteboard_DoodleTouchGestureListener_list.add(mTouchGestureListener);
        } else {
            mDoodleParams_list.add(mDoodleParams);
            mDoodle_list.add(mDoodle);
            mDoodleView_list.add(mDoodleView);
            mDoodleTouchGestureListener_list.add(mTouchGestureListener);
        }

        set_btn_doodle_num();

        if(isPlay) {
            drawTrack_rxJava();
        }
    }

    /**
     * 包裹DoodleView，监听相应的设置接口，以改变UI状态
     */
    private class DoodleViewWrapper extends DoodleView {

        public DoodleViewWrapper(Context context, Bitmap bitmap, boolean optimizeDrawing, IDoodleListener listener) {
            super(context, bitmap, optimizeDrawing, listener);
        }
    }

    private void prevPage() {
        if(voiceRecorder.getRecordStatus() != VoiceRecorder.VOICE_RECORDER_START) {
            ToastUtil.initToast("只有在录制过程中才可以切换页");
            return;
        }

        switchPage(false, false);
    }

    private void nextPage() {
        if(voiceRecorder.getRecordStatus() != VoiceRecorder.VOICE_RECORDER_START) {
            ToastUtil.initToast("只有在录制过程中才可以切换页");
            return;
        }
        switchPage(true, false);
    }

    private void switchPage(boolean isNext, boolean isPlay) {
        if(isGliding) {
            ToastUtil.initToast("正在加载图片，请稍后");
            return;
        }
        if(isPlay) {
            rxjava_disposable();
        }
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                switchPage_real(isNext, isPlay);
            }
        });
    }

    private void switchPage_real(boolean isNext, boolean isPlay) {
        if(isNext) {
            if(isWhiteboard) {
                if (mWhiteboard_DoodleImageIndex >= mWhiteboard_DoodleView_list.size() - 1
                        && mWhiteboard_DoodleView_list.size() >= mWhiteboardMaxPage) {
                    ToastUtil.initToast("已经是最后一页，无法下一页");
                    return;
                }
            } else {
                if (mDoodleImageIndex >= mDoodleImagePath.size() - 1) {
                    ToastUtil.initToast("已经是最后一页，无法下一页");
                    return;
                }
            }
            if(!isPlay) {
                if(isEraser) {
                    switchEraser();
                }
                writeActionToFile("ACTION_NEXT_PAGE");
            }
            if(isWhiteboard) {
                mWhiteboard_DoodleImageIndex++;
            } else {
                mDoodleImageIndex++;
            }
        } else {
            if(isWhiteboard) {
                if (mWhiteboard_DoodleImageIndex == 0) {
                    ToastUtil.initToast("已经是第一页，无法上一页");
                    return;
                }
            } else {
                if (mDoodleImageIndex == 0) {
                    ToastUtil.initToast("已经是第一页，无法上一页");
                    return;
                }
            }

            if(!isPlay) {
                if(isEraser) {
                    switchEraser();
                }
                writeActionToFile("ACTION_PREV_PAGE");
            }
            if(isWhiteboard) {
                mWhiteboard_DoodleImageIndex--;
            } else {
                mDoodleImageIndex--;
            }
        }
        if(isWhiteboard) {
            for (int i = 0; i < mWhiteboard_DoodleView_list.size(); i++) {
                mWhiteboard_DoodleView_list.get(i).setVisibility(View.GONE);
                mWhiteboard_DoodleTouchGestureListener_list.get(i).setSupportDoodle(false); //禁止涂鸦
            }
            if (mWhiteboard_DoodleImageIndex >= mWhiteboard_DoodleView_list.size()) {
                initDoodleData(isPlay);
            } else {
                mWhiteboard_DoodleView_list.get(mWhiteboard_DoodleImageIndex).setVisibility(View.VISIBLE);
                if(isPlay) {
                    drawTrack_rxJava();
                } else {
                    mWhiteboard_DoodleTouchGestureListener_list.get(mWhiteboard_DoodleImageIndex).setSupportDoodle(true); //禁止涂鸦
                }

            }
        } else {
            for (int i = 0; i < mDoodleView_list.size(); i++) {
                mDoodleView_list.get(i).setVisibility(View.GONE);
                mDoodleTouchGestureListener_list.get(i).setSupportDoodle(false); //禁止涂鸦
            }
            if (mDoodleImageIndex >= mDoodleView_list.size()) {
                downLoadImg(isPlay); //这个函数中也有drawTrack_pub();
            } else {
                mDoodleView_list.get(mDoodleImageIndex).setVisibility(View.VISIBLE);
                if(isPlay) {
                    drawTrack_rxJava();
                } else {
                    mDoodleTouchGestureListener_list.get(mDoodleImageIndex).setSupportDoodle(true); //禁止涂鸦
                }

            }
        }

        set_btn_doodle_num();
    }

    private void switchEraser() {
        isEraser = !isEraser;
        if(isEraser) {
            writeActionToFile("ACTION_PEN_ERASER");
            if(isWhiteboard) {
                mWhiteboard_Doodle_list.get(mWhiteboard_DoodleImageIndex).setPen(DoodlePen.ERASER);
            } else {
                mDoodle_list.get(mDoodleImageIndex).setPen(DoodlePen.ERASER);
            }
            btn_eraser.setText("切换到画笔");

        } else {
            writeActionToFile("ACTION_PEN_BRUSH");
            if(isWhiteboard) {
                mWhiteboard_Doodle_list.get(mWhiteboard_DoodleImageIndex).setPen(DoodlePen.BRUSH);
            } else {
                mDoodle_list.get(mDoodleImageIndex).setPen(DoodlePen.BRUSH);
            }
            btn_eraser.setText("切换到橡皮檫");
        }
    }

    private void switchWhiteboard(boolean isPlay) {
        if(!isPlay && voiceRecorder.getRecordStatus() != VoiceRecorder.VOICE_RECORDER_START) {
            ToastUtil.initToast("只有在正在录制时，才能切换白板");
            return;
        }
        if(isGliding) {
            ToastUtil.initToast("正在加载图片，请稍后");
            return;
        }
        if(isPlay) {
            rxjava_disposable();
        }
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                switchWhiteboard_real(isPlay);
            }
        });
    }

    private void switchWhiteboard_real(boolean isPlay) {
        if(!isPlay) {
            if (isEraser) {
                switchEraser();
            }
        }
        isWhiteboard = !isWhiteboard;
        set_btn_Whiteboard_text();
        if(!isPlay) {
            writeActionToFile("ACTION_SWITCH_WHITEBOARD");
        }
        if(isWhiteboard) {
            mDoodleView_list.get(mDoodleImageIndex).setVisibility(View.GONE);
            mDoodleTouchGestureListener_list.get(mDoodleImageIndex).setSupportDoodle(false); //禁止涂鸦
            if(mWhiteboard_Doodle_bitmap == null) {
                downLoadImg(isPlay);
            } else {
                mWhiteboard_DoodleView_list.get(mWhiteboard_DoodleImageIndex).setVisibility(View.VISIBLE);
                if(isPlay) {
                    drawTrack_rxJava();
                } else {
                    mWhiteboard_DoodleTouchGestureListener_list.get(mWhiteboard_DoodleImageIndex).setSupportDoodle(true); //禁止涂鸦
                }
            }
        } else {
            mWhiteboard_DoodleView_list.get(mWhiteboard_DoodleImageIndex).setVisibility(View.GONE);
            mWhiteboard_DoodleTouchGestureListener_list.get(mWhiteboard_DoodleImageIndex).setSupportDoodle(false); //禁止涂鸦

            mDoodleView_list.get(mDoodleImageIndex).setVisibility(View.VISIBLE);
            if(isPlay) {
                drawTrack_rxJava();
            } else {
                mDoodleTouchGestureListener_list.get(mDoodleImageIndex).setSupportDoodle(true); //禁止涂鸦
            }

        }

        set_btn_doodle_num();
    }

    private void set_btn_Whiteboard_text() {
        if(isWhiteboard) {
            btn_Whiteboard.setText("切换到试题");
        } else {
            btn_Whiteboard.setText("切换到白板");
        }
    }

    private void writeEventTofile(MotionEvent e) {
        if(!fileOperate()) {
            return;
        }
        if(e != null) {
            String action = "ACTION_DOWN";
            if(e.getAction() == MotionEvent.ACTION_MOVE) {
                action = "ACTION_MOVE";
            } else if(e.getAction() == MotionEvent.ACTION_UP) {
                action = "ACTION_UP";
            }
            trackId++;
            TrackBean trackBean = new TrackBean(trackId, e.getX(), e.getY(), action, mRecorderTime, isWhiteboard ? mWhiteboard_DoodleImageIndex : mDoodleImageIndex, isWhiteboard, fl_width, fl_height);
            lineWriteFile(trackFilePath, JsonUtils.toJson(trackBean));

        }
    }

    private void writeActionToFile(String action) {
        if(!fileOperate()) {
            return;
        }
        trackId++;
        TrackBean trackBean = new TrackBean(trackId, -1, -1, action, mRecorderTime, isWhiteboard ? mWhiteboard_DoodleImageIndex : mDoodleImageIndex, isWhiteboard, fl_width, fl_height);
        lineWriteFile(trackFilePath, JsonUtils.toJson(trackBean));
    }

    private void lineWriteFile(String filePath, String json){
        try {
            FileWriter fw = new FileWriter(new File(filePath), true);
            //写入中文字符时会出现乱码
            BufferedWriter bw=new BufferedWriter(fw);
            //BufferedWriter  bw=new BufferedWriter(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File("E:/phsftp/evdokey/evdokey_201103221556.txt")), "UTF-8")));
            bw.write(json+"\r\n");
            bw.close();
            fw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    private void lineReadFile(){
        Observable.create(new ObservableOnSubscribe<Boolean>() {
            @Override
            public void subscribe(ObservableEmitter<Boolean> emitter) throws Exception {
                try {
                    trackBeanList.clear();
                    trackIndex_prev = 0;
                    trackIndex_next = 0;
                    FileReader fr = new FileReader(trackFilePath);
                    BufferedReader br=new BufferedReader(fr);
                    String line="";

                    while ((line=br.readLine())!=null  && !"".equals(line.trim()) && JsonUtils.isGoodJson(line)) {
                        TrackBean trackBean = JsonUtils.fromJson(line, TrackBean.class);
                        trackBeanList.add(trackBean);
                    }
                    //LogUtils.i(trackBeanList.toString());
                    br.close();
                    fr.close();
                    //testTrackEvent();
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                    emitter.onError(new Throwable("读取轨迹文件失败！！" + e.getMessage()));
                    emitter.onComplete();
                } catch (IOException e) {
                    e.printStackTrace();
                    emitter.onError(new Throwable("读取轨迹文件失败！！" + e.getMessage()));
                    emitter.onComplete();
                }finally {
                    emitter.onNext(true);
                    emitter.onComplete();
                }
            }
        }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<Boolean>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(Boolean aBoolean) {
                playBinder.callPlayMusic();
                LogUtils.i("读取文件成功");
                drawTrack_rxJava();
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        });
    }

    private void drawTrack_real() {
        if(trackIndex_prev >= trackBeanList.size()) {
            LogUtils.i("出错了：trackIndex_prev >= trackBeanList.size()");
            rxjava_disposable();
            return;
        }
        TrackBean trackBean = trackBeanList.get(trackIndex_prev);
        trackIndex_prev++;
        //LogUtils.i("测试16--trackIndex_prev=" + trackIndex_prev + ", trackIndex_next=" + trackIndex_next);
        //LogUtils.i(trackBean.toString());
        float f_scale_w = 0;
        float f_scale_h = 0;
        float f_scale = 0;
        if(trackBean.getFl_width() == 0) {
            f_scale_w = 0;
        } else {
            f_scale_w = 1.0f * fl_width / trackBean.getFl_width();
        }

        if(trackBean.getFl_height() == 0) {
            f_scale_h = 0;
        } else {
            f_scale_h = 1.0f * fl_height / trackBean.getFl_height();
        }

        //LogUtils.e("录制UI和播放UI的宽比：" + f_scale_w + "，高比：" + f_scale_h);
        if(f_scale_w == 0 || f_scale_h == 0) {
            f_scale = 1;
        } else {
            if(f_scale_w - f_scale_h > 0) {
                f_scale = f_scale_h;
            } else {
                f_scale = f_scale_w;
            }
        }


        if("ACTION_DOWN".equals(trackBean.getAction())) {
            if(isWhiteboard) {
                mWhiteboard_DoodleTouchGestureListener_list.get(mWhiteboard_DoodleImageIndex).r_onDown(trackBean.getX() * f_scale, trackBean.getY() * f_scale);
                mWhiteboard_DoodleTouchGestureListener_list.get(mWhiteboard_DoodleImageIndex).r_onScrollBegin(trackBean.getX() * f_scale, trackBean.getY() * f_scale);
            } else {
                mDoodleTouchGestureListener_list.get(mDoodleImageIndex).r_onDown(trackBean.getX() * f_scale, trackBean.getY() * f_scale);
                mDoodleTouchGestureListener_list.get(mDoodleImageIndex).r_onScrollBegin(trackBean.getX() * f_scale, trackBean.getY() * f_scale);
            }

        } else if ("ACTION_MOVE".equals(trackBean.getAction())) {
            if(isWhiteboard) {
                mWhiteboard_DoodleTouchGestureListener_list.get(mWhiteboard_DoodleImageIndex).r_onScroll(trackBean.getX() * f_scale, trackBean.getY() * f_scale);
            } else {
                mDoodleTouchGestureListener_list.get(mDoodleImageIndex).r_onScroll(trackBean.getX() * f_scale, trackBean.getY() * f_scale);
            }

        } else if("ACTION_UP".equals(trackBean.getAction())) {
            if(isWhiteboard) {
                mWhiteboard_DoodleTouchGestureListener_list.get(mWhiteboard_DoodleImageIndex).r_onScrollEnd(trackBean.getX() * f_scale, trackBean.getY() * f_scale);
            } else {
                mDoodleTouchGestureListener_list.get(mDoodleImageIndex).r_onScrollEnd(trackBean.getX() * f_scale, trackBean.getY() * f_scale);
            }

        } else if ("ACTION_PEN_ERASER".equals(trackBean.getAction())) {
            if(isWhiteboard) {
                mWhiteboard_Doodle_list.get(mWhiteboard_DoodleImageIndex).setPen(DoodlePen.ERASER);
            } else {
                mDoodle_list.get(mDoodleImageIndex).setPen(DoodlePen.ERASER);
            }

        } else if ("ACTION_PEN_BRUSH".equals(trackBean.getAction())) {
            if(isWhiteboard) {
                mWhiteboard_Doodle_list.get(mWhiteboard_DoodleImageIndex).setPen(DoodlePen.BRUSH);
            } else {
                mDoodle_list.get(mDoodleImageIndex).setPen(DoodlePen.BRUSH);
            }

        } else if("ACTION_PREV_PAGE".equals(trackBean.getAction())) {
            LogUtils.i("播放轨迹上一页：" + trackBean.getId());
            switchPage(false, true);
        } else if ("ACTION_NEXT_PAGE".equals(trackBean.getAction())) {
            LogUtils.i("播放轨迹下一页：" + trackBean.getId());
            switchPage(true, true);
        } else if ("ACTION_SWITCH_WHITEBOARD".equals(trackBean.getAction())) {
            LogUtils.i("切换白板：" + trackBean.getId());
            switchWhiteboard(true);
        }else if("ACTION_UNDO".equals(trackBean.getAction())) {
            drawTrack_undo(true);
        } else if("ACTION_REDO".equals(trackBean.getAction())) {
            drawTrack_undo(false);
        }
    }

    private void drawTrack_undo(boolean isUn) {
        if(isUn) {
            if(isWhiteboard) {
                if (!mWhiteboard_Doodle_list.get(mWhiteboard_DoodleImageIndex).undo()) {
                    ToastUtil.initToast("无法再撤销");
                }
            } else {
                if (!mDoodle_list.get(mDoodleImageIndex).undo()) {
                    ToastUtil.initToast("无法再撤销");
                }
            }

        } else {
            if(isWhiteboard) {
                if (!mWhiteboard_Doodle_list.get(mWhiteboard_DoodleImageIndex).redo(1)) {
                    ToastUtil.initToast("无法再反撤销");
                }
            } else {
                if (!mDoodle_list.get(mDoodleImageIndex).redo(1)) {
                    ToastUtil.initToast("无法再反撤销");
                }
            }
        }
    }


    private void drawTrack_rxJava() {
        rxjava_disposable();

        Observable.interval(handler_time_pre*10, (int)(handler_time_pre/handler_time_scale), TimeUnit.MILLISECONDS)
                .subscribeOn(Schedulers.single())
                .subscribe(new Observer < Long > () {
                    @Override
                    public void onSubscribe(Disposable d) {
                        disposable = d;
                    }

                    @Override
                    public void onNext(Long aLong) {
                        //LogUtils.i("测试1");
                        /*if(isPx30Eink) {
                            drawTrack_rxJava_next();
                        } else {*/
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    drawTrack_rxJava_next();
                                }
                            });
                        //}
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    private void drawTrack_rxJava_next() {
        if(isGliding) {
            return;
        }
        //LogUtils.i("测试2--trackIndex_prev = " + trackIndex_prev + ", trackIndex_next = " + trackIndex_next);
        if(trackIndex_prev == trackIndex_next) {
            int next_time = 0;
            if(isLargeJumping) {
                next_time = largeJumpTime;
            } else {
                next_time = playCurrentPosition_next;
            }
            final int seekTime = next_time;
            //LogUtils.i("测试3--next_time = " +next_time + ", playCurrentPosition_prev = " + playCurrentPosition_prev);
            if(playCurrentPosition_prev <= next_time) {
                //LogUtils.i("测试4--trackBeanList.size() = " + trackBeanList.size());
                if(trackIndex_next < trackBeanList.size()) {
                    //LogUtils.i("测试5");
                    String action = "";
                    for(int i = trackIndex_next; i < trackBeanList.size(); i++) {
                        //LogUtils.i("测试6");
                        TrackBean trackBean = trackBeanList.get(i);
                        if(trackBean.getTime() <= next_time) {
                            trackIndex_next = i + 1;
                            action = trackBean.getAction();
                            //LogUtils.i("测试7--trackIndex_next = " + trackIndex_next);
                        } else if("ACTION_DOWN".equals(action) || "ACTION_MOVE".equals(action)) {
                            trackIndex_next = i + 1;
                            action = trackBean.getAction();
                            //LogUtils.i("测试8--trackIndex_next = " + trackIndex_next);
                        } else {
                            //LogUtils.i("测试9");
                            break;
                        }
                    }
                }
            }
            //LogUtils.i("测试10--trackIndex_prev=" + trackIndex_prev + ", trackIndex_next=" + trackIndex_next);
            if(trackIndex_prev == trackIndex_next) {
                //LogUtils.i("测试11");
                if(isLargeJumping) {
                    //LogUtils.i("测试17");
                    isLargeJumping = false;
                    largeJumpCount = 0;
                    handler_time_scale = 1;
                    rxjava_disposable();
                    drawTrack_rxJava();
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            callSeekTo(seekTime);
                            callResumeMusic();
                        }
                    });
                }
                if(trackIndex_next == trackBeanList.size()) {
                    //LogUtils.i("测试12");
                    rxjava_disposable();
                }
                return;
            } else {
                if(trackIndex_next >= trackBeanList.size()) {
                    playCurrentPosition_prev = mDuration;
                } else {
                    playCurrentPosition_prev = trackBeanList.get(trackIndex_next).getTime();
                }

                //LogUtils.i("测试14--playCurrentPosition_prev = " + playCurrentPosition_prev);
            }


        }
        //LogUtils.i("测试15--trackIndex_prev=" + trackIndex_prev + ", trackIndex_next=" + trackIndex_next);
        if(trackIndex_prev > trackIndex_next) {
            LogUtils.e("出错了，trackIndex_prev > trackIndex_next");
            rxjava_disposable();
            return;
        }
        //LogUtils.i("线程时间：" + (System.currentTimeMillis() - PlayService_2.testTime_2) + ", 线程名：" + Thread.currentThread().getName());
        //PlayService_2.testTime_2 = System.currentTimeMillis();
        if(trackIndex_prev >= trackBeanList.size()) {
            rxjava_disposable();
        }
        drawTrack_real();
    }

    private void rxjava_disposable() {
        if(disposable != null && !disposable.isDisposed()) {
            disposable.dispose();
            disposable = null;
        }
    }

    private void delay_rxjava_disposable() {
        Observable.just(1)
                .delay(200, TimeUnit.MILLISECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer < Integer > () {
                    @Override
                    public void onSubscribe(Disposable d) {
                    }

                    @Override
                    public void onNext(Integer integer) {
                        rxjava_disposable();
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {
                    }
                });
    }
    private void delay_largeJumpCountMax() {
        Observable.just(1)
                .delay(100, TimeUnit.MILLISECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer < Integer > () {
                    @Override
                    public void onSubscribe(Disposable d) {
                    }

                    @Override
                    public void onNext(Integer integer) {
                        drawTrack_rxJava_next();
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {
                    }
                });
    }

}
